﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using EvaluationSystem.DAO;
using System.Data;
using EvaluationSystem.Exceptions;

namespace EvaluationSystem.ConfigurationPages.EvaluationItemsPages
{
    public partial class EvaluationItemsPage : System.Web.UI.Page
    {
        EvaluationItemsManager evaluationManager = new EvaluationItemsManager();
        SummaryManager summaryManager = new SummaryManager();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Utility.IsLogin(this.Page))
            {
#if !DEBUG
                Response.Redirect("../Default.aspx");
#endif
            }
        }

        protected void Store_RefreshData(object sender, StoreRefreshDataEventArgs e)
        {
            this.objectDataSource.SelectParameters[Constants.Start].DefaultValue = e.Start.ToString();
            this.objectDataSource.SelectParameters[Constants.Limit].DefaultValue = e.Limit.ToString();
            this.objectDataSource.SelectParameters[Constants.Sort].DefaultValue = e.Sort;
            this.objectDataSource.SelectParameters[Constants.Dir].DefaultValue = e.Dir.ToString();

            this.store.DataBind();
        }

        protected void ObjectDataSource_Selected(object sender, ObjectDataSourceStatusEventArgs e)
        {
            (this.store.Proxy[0] as PageProxy).Total = (int)e.OutputParameters["count"];
        }

        public List<EvaluationItem> GetEvaluationFilter(int start, int limit, string sort, string dir, out int count)
        {
            DataTable dt = evaluationManager.GetAllEvaluationItems();
            IEnumerable<DataRow> rows = null;
            if (start >= 0 && limit > 0)
            {
                rows = dt.Select().Skip(start).Take(limit);
            }

            count = evaluationManager.GetEvaluationItemsCount(this.Page);
            List<EvaluationItem> result = new List<EvaluationItem>(limit);
            foreach (DataRow row in rows)
            {
                result.Add(new EvaluationItem
                {
                    Id = (int)row["Id"],
                    SummaryName = (string)row["SummaryName"],
                    Evaluation = (string)row["Evaluation"],
                });
            }
            return result;
        }

        [DirectMethod]
        public void DeleteEvaluation(string id)
        {
            try
            {
                bool isSuccess = evaluationManager.DeleteEvaluationById(id);
                if (isSuccess)
                {
                    evaluationManager.GetEvaluationItemsCount(this.Page, true);
                    X.MessageBox.Notify(Constants.Noticfy, "删除成功.").Show();
                    gpEvaluation.Reload();
                }
                else
                {
                    X.MessageBox.Alert(Constants.Noticfy, "操作出错，请重新尝试或联系开发人员.").Show();
                }
            }
            catch (Exception ex)
            {
                X.MessageBox.Alert(Constants.Noticfy, ex.Message).Show();
            }
        }

        [DirectMethod]
        public void EditEvaluation(string id, string summaryName, string evaluation)
        {
            Window win = CreateWindow(id,summaryName,evaluation);
            win.Render(this.Form);
            win.Show();
        }

        [DirectMethod]
        public void Reload()
        {
            gpEvaluation.Reload();
        }

        private Window CreateWindow(string id, string summaryName, string evaluation)
        {
            Window win = new Window()
            {
                Closable = true,
                Resizable = false,
                Height = 300,
                Icon = Icon.Application,
                Title = "修改评分指标内容",
                Draggable = true,
                Width = 400,
                Modal = true,
                Padding = 5,
                CloseAction = Ext.Net.CloseAction.Close,
                Layout = "AnchorLayout",
                ID = "EvaluationAddingWindow"
            };
            win.Listeners.Close.Handler = "Ext.net.DirectMethods.Reload();";
            TextArea txtEvalutionItemName = new TextArea()
            {
                ID = "txtEvalutionItemName",
                FieldLabel = "评分指标内容",
                AllowBlank = false,
                BlankText = "请输入评分指标内容.",
                AnchorHorizontal = "100%",
                MaxLength = 500,
                Height = 200
            };
            win.Items.Add(txtEvalutionItemName);
            ComboBox cbbSummary = new ComboBox()
            {
                AnchorHorizontal = "100%",
                TriggerIcon = TriggerIcon.SimpleArrowDown,
                FieldLabel = "评分指标项",
                AllowBlank = false,
                BlankText = "请选评分指标项.",
                ID = "cbbSummary"
            };
            win.Items.Add(cbbSummary);
            Ext.Net.Button btnSave = new Ext.Net.Button()
            {
                ID = "btnSave",
                Text = "保存",
                Icon = Icon.Accept
            };
            btnSave.Listeners.Click.Handler = " if (!#{txtEvalutionItemName}.validate() || !#{cbbSummary}.validate()) { Ext.Msg.alert('Error','请填写必要内容.');return false; }";
            btnSave.Listeners.Click.Handler = "Ext.net.DirectMethods.btnSave_Click(" + id + ",#{txtEvalutionItemName}.getValue(),#{cbbSummary}.value);";
            //btnSave.Click.DirectEvents.Click..Event += new ComponentDirectEvent.DirectEventHandler(btnSave_Click);
            btnSave.DirectEvents.Click.EventMask.ShowMask = true;
            btnSave.DirectEvents.Click.EventMask.Msg = "保存中...";
            btnSave.DirectEvents.Click.EventMask.MinDelay = 500;
            win.Buttons.Add(btnSave);

            Ext.Net.Button btnCancel = new Ext.Net.Button()
            {
                ID = "btnCancel",
                Text = "关闭",
                Icon = Icon.Decline
            };
            btnCancel.Listeners.Click.Handler = "#{EvaluationAddingWindow}.close();";
            win.Buttons.Add(btnCancel);

            InitSummary(cbbSummary, summaryName);
            txtEvalutionItemName.Text = evaluation;

            return win;
        }

        [DirectMethod]
        public  void btnSave_Click(string id,string evaluation, string summaryId)
        {
            try
            {
                bool isSuccess = evaluationManager.UpdateEvaluationById(id, summaryId, evaluation);
                if (isSuccess)
                {
                    X.MessageBox.Notify(Constants.Noticfy, "修改评分指标内容成功.").Show();
                }
                else
                {
                    X.MessageBox.Alert(Constants.Noticfy, "保存出错，请重新尝试或联系开发人员.").Show();
                }
            }
            catch (ExistEvaluationException ex)
            {
                X.MessageBox.Alert(Constants.Noticfy, ex.Message).Show();
            }
        }

        protected void InitSummary(ComboBox cbbSummary, string summaryName)
        {
            DataTable dt = summaryManager.GetAllSummary();
            int index = -1;
            foreach (DataRow row in dt.Rows)
            {
                index++;
                cbbSummary.Items.Add(new Ext.Net.ListItem((string)row["SummaryName"], row["Id"].ToString()));
                if (summaryName.Equals((string)row["SummaryName"]))
                {
                    cbbSummary.SelectedIndex = index;
                }
            }
        }
    }
}